package cn.pconline.autoclub.util;

import com.alibaba.fastjson.JSONObject;

/**
 * 用于帮助返回JSON数据的工具类（官方车友会统一使用这个）
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
public class Result {

    private JSONObject me;

    public Result() {
        me = new JSONObject();
    }

    public String getString(String key) {
        return me.getString(key);
    }

    public Result set(String key, Object v) {
        me.put(key, v);
        return this;
    }

    /**
     * 只设置基本分页信息不会设置resultList
     *
     * @param pager
     * @return
     */
    public static Result pager(Pager pager) {
        return new Result().set("pageCount", pager.getPageCount())
                .set("pageNo", pager.getPageNo())
                .set("pageSize", pager.getPageSize())
                .set("total", pager.getTotal());
    }

    public static Result instance() {
        return new Result();
    }

    public static Result noLogin() {
        return new Result().set("code", AppUtils.STATUS_NOLOGIN_ERROR).set("message", "未登录");
    }

    public static Result noPermission() {
        return noPermission("");
    }

    public static Result noPermission(String msg) {
        return new Result().set("code", AppUtils.STATUS_PERMISSIONS_ERROR).set("message", msg);
    }

    public static Result dataError() {
        return dataError("");
    }

    public static Result dataError(String msg) {
        return new Result().set("code", AppUtils.STATUS_DATA_ERROR).set("message", msg);
    }

    public static Result success() {
        return success("");
    }

    public static Result success(String msg) {
        return new Result().set("code", AppUtils.STATUS_OK).set("message", msg);
    }

    public static Result success(Object data) {
        if (data instanceof Result) {
            data = ((Result) data).me;// data不传jsonObject的话序列化会失败，暂时这些处理
        }
        return new Result().set("code", AppUtils.STATUS_OK).set("data", data);
    }

    public static Result success(String key, Object data) {
        Result rs = Result.instance().set(key, data);
        return success(rs);
    }

    public static Result error(String msg) {
        return new Result().set("code", AppUtils.STATUS_FAIL).set("message", msg);
    }

    @Override
    public String toString() {
        return me.toJSONString();
    }
}
